package com.yh.zz_hlj.print;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.WriterException;
import com.yh.zz_hlj.R;
import com.yh.zz_hlj.common.UIHelper;
import com.yh.zz_hlj.modules.bean.SimpleBackPage;
import com.zxing.encoding.EncodingHandler;

import HPRTAndroidSDK.HPRTPrinterHelper;
import HPRTAndroidSDK.IPort;
import HPRTAndroidSDK.PublicFunction;

public class Activity_Main extends Activity {
    private Context thisCon = null;
    private BluetoothAdapter mBluetoothAdapter;
    private PublicFunction PFun = null;

    private Button btnBT = null;

    private Spinner spnPrinterList = null;
    private TextView txtTips = null;
    private ImageView image;
    private Button btnOpenCashDrawer = null;
    private Button btnSampleReceipt = null;
    private Button btn1DBarcodes = null;
    private Button btnQRCode = null;
    private Button btnPDF417 = null;
    private Button btnCut = null;
    private Button btnPageMode = null;
    private Button btnImageManage = null;
    private Button btnGetRemainingPower = null;

    private EditText edtTimes = null;

    private ArrayAdapter arrPrinterList;
    private static HPRTPrinterHelper HPRTPrinter = new HPRTPrinterHelper();
    private String ConnectType = "";
    private String PrinterName = "";
    private String PortParam = "";

    private UsbManager mUsbManager = null;
    private UsbDevice device = null;
    private static final String ACTION_USB_PERMISSION = "com.HPRTSDKSample";
    private PendingIntent mPermissionIntent = null;
    private static IPort Printer = null;
    private Handler handler;
    private ProgressDialog dialog;
    public static String paper = "0";
    private String mFBillNo;
    private String OutStock;
    private Bitmap mQrCode;
    private String[] mFNumbers;
    private String[] mFXBWSX;
    private String[] mFOUT;
    private boolean isSave = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mains);
        mFBillNo = getIntent().getStringExtra("fBillNo");
        OutStock = getIntent().getStringExtra("OutStock");
        mFNumbers = getIntent().getStringArrayExtra("FNumber");
        mFXBWSX = getIntent().getStringArrayExtra("FXBWSX");

        mFOUT = getIntent().getStringArrayExtra("FOUT");

        try {
            thisCon = this.getApplicationContext();

            btnBT = (Button) findViewById(R.id.btnBT);

            spnPrinterList = (Spinner) findViewById(R.id.spn_printer_list);
            txtTips = (TextView) findViewById(R.id.txtTips);
            image = (ImageView) findViewById(R.id.image);
            try {
                if (!TextUtils.isEmpty(mFBillNo)) {
                    mQrCode = EncodingHandler.createQRCode(mFBillNo, 500);
                    image.setImageBitmap(mQrCode);
                } else {
                    mQrCode = EncodingHandler.createQRCode("12345678", 500);
                    image.setImageBitmap(mQrCode);
                }
            } catch (WriterException e) {
                e.printStackTrace();
            }
            btnSampleReceipt = (Button) findViewById(R.id.btnSampleReceipt);
            btnOpenCashDrawer = (Button) findViewById(R.id.btnOpenCashDrawer);
            btn1DBarcodes = (Button) findViewById(R.id.btn1DBarcodes);
            btnQRCode = (Button) findViewById(R.id.btnQRCode);
            btnPDF417 = (Button) findViewById(R.id.btnPDF417);
            btnCut = (Button) findViewById(R.id.btnCut);
            btnPageMode = (Button) findViewById(R.id.btnPageMode);
            btnImageManage = (Button) findViewById(R.id.btnImageManage);
            btnGetRemainingPower = (Button) findViewById(R.id.btnGetRemainingPower);
            btnGetStatus = (Button) findViewById(R.id.btnGetStatus);

            mPermissionIntent = PendingIntent.getBroadcast(thisCon, 0, new Intent(ACTION_USB_PERMISSION), 0);
            IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
            thisCon.registerReceiver(mUsbReceiver, filter);

            PFun = new PublicFunction(thisCon);
            InitSetting();
            InitCombox();
            this.spnPrinterList.setOnItemSelectedListener(new OnItemSelectedPrinter());
            //Enable Bluetooth
            EnableBluetooth();
            handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    // TODO Auto-generated method stub
                    super.handleMessage(msg);
                    if (msg.what == 1) {
                        Toast.makeText(thisCon, "succeed", Toast.LENGTH_SHORT).show();
                        dialog.cancel();
                    } else {
                        Toast.makeText(thisCon, "failure", Toast.LENGTH_SHORT).show();
                        dialog.cancel();
                    }
                }
            };
        } catch (Exception e) {
        }
    }

    private void InitSetting() {
        String SettingValue = "";
        SettingValue = PFun.ReadSharedPreferencesData("Codepage");
        if (SettingValue.equals(""))
            PFun.WriteSharedPreferencesData("Codepage", "0,PC437(USA:Standard Europe)");

        SettingValue = PFun.ReadSharedPreferencesData("Cut");
        if (SettingValue.equals(""))
            PFun.WriteSharedPreferencesData("Cut", "0");    //0:��ֹ,1:��ӡǰ,2:��ӡ��

        SettingValue = PFun.ReadSharedPreferencesData("Cashdrawer");
        if (SettingValue.equals(""))
            PFun.WriteSharedPreferencesData("Cashdrawer", "0");

        SettingValue = PFun.ReadSharedPreferencesData("Buzzer");
        if (SettingValue.equals(""))
            PFun.WriteSharedPreferencesData("Buzzer", "0");

        SettingValue = PFun.ReadSharedPreferencesData("Feeds");
        if (SettingValue.equals(""))
            PFun.WriteSharedPreferencesData("Feeds", "0");
        String paper = PFun.ReadSharedPreferencesData("papertype");
        if (!"".equals(paper)) {
            Activity_Main.paper = paper;
        }
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        String paper = PFun.ReadSharedPreferencesData("papertype");
        if (!"".equals(paper)) {
            Activity_Main.paper = paper;
        }
        String[] arrpaper = getResources().getStringArray(R.array.activity_main_papertype);
        if ("1".equals(Activity_Main.paper)) {
            btnOpenCashDrawer.setText(getResources().getString(R.string.activity_esc_function_btnopencashdrawer) + ":" + arrpaper[1]);
        } else {
            btnOpenCashDrawer.setText(getResources().getString(R.string.activity_esc_function_btnopencashdrawer) + ":" + arrpaper[0]);
        }
    }

    //add printer list
    private void InitCombox() {
        try {
            arrPrinterList = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
            String strSDKType = thisCon.getString(R.string.sdk_type);
            if (strSDKType.equals("all"))
                arrPrinterList = ArrayAdapter.createFromResource(this, R.array.printer_list_cpcl, android.R.layout.simple_spinner_item);
            if (strSDKType.equals("hprt"))
                arrPrinterList = ArrayAdapter.createFromResource(this, R.array.printer_list_hprt, android.R.layout.simple_spinner_item);
            if (strSDKType.equals("mkt"))
                arrPrinterList = ArrayAdapter.createFromResource(this, R.array.printer_list_mkt, android.R.layout.simple_spinner_item);
            if (strSDKType.equals("mprint"))
                arrPrinterList = ArrayAdapter.createFromResource(this, R.array.printer_list_mprint, android.R.layout.simple_spinner_item);
            if (strSDKType.equals("sycrown"))
                arrPrinterList = ArrayAdapter.createFromResource(this, R.array.printer_list_sycrown, android.R.layout.simple_spinner_item);
            if (strSDKType.equals("mgpos"))
                arrPrinterList = ArrayAdapter.createFromResource(this, R.array.printer_list_mgpos, android.R.layout.simple_spinner_item);
            if (strSDKType.equals("ds"))
                arrPrinterList = ArrayAdapter.createFromResource(this, R.array.printer_list_ds, android.R.layout.simple_spinner_item);
            if (strSDKType.equals("cst"))
                arrPrinterList = ArrayAdapter.createFromResource(this, R.array.printer_list_cst, android.R.layout.simple_spinner_item);
            if (strSDKType.equals("other"))
                arrPrinterList = ArrayAdapter.createFromResource(this, R.array.printer_list_other, android.R.layout.simple_spinner_item);
            arrPrinterList.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            PrinterName = arrPrinterList.getItem(0).toString();
            spnPrinterList.setAdapter(arrPrinterList);
        } catch (Exception e) {
            Log.e("HPRTSDKSample", (new StringBuilder("Activity_Main --> InitCombox ")).append(e.getMessage()).toString());
        }
    }

    private class OnItemSelectedPrinter implements OnItemSelectedListener {
        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

            PrinterName = arrPrinterList.getItem(arg2).toString();
            HPRTPrinter = new HPRTPrinterHelper(thisCon, PrinterName);
            CapturePrinterFunction();
            //		GetPrinterProperty();
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub
        }
    }

    //EnableBluetooth
    private boolean EnableBluetooth() {
        boolean bRet = false;
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter != null) {
            if (mBluetoothAdapter.isEnabled())
                return true;
            mBluetoothAdapter.enable();
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (!mBluetoothAdapter.isEnabled()) {
                bRet = true;
                Log.d("PRTLIB", "BTO_EnableBluetooth --> Open OK");
            }
        } else {
            Log.d("HPRTSDKSample", (new StringBuilder("Activity_Main --> EnableBluetooth ").append("Bluetooth Adapter is null.")).toString());
        }
        return bRet;
    }

    //call back by scan bluetooth printer
    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        try {
            String strIsConnected;
            switch (resultCode) {
                case HPRTPrinterHelper.ACTIVITY_CONNECT_BT:
                    String strBTAddress = "";
                    strIsConnected = data.getExtras().getString("is_connected");
                    if (strIsConnected.equals("NO")) {
                        txtTips.setText(thisCon.getString(R.string.activity_main_scan_error));
                        Toast.makeText(thisCon, "扫描失败，建议重启蓝牙 ！", Toast.LENGTH_SHORT).show();
                        return;
                    } else {
                        txtTips.setText(thisCon.getString(R.string.activity_main_connected));
                        Toast.makeText(thisCon, "连接成功 ！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                case HPRTPrinterHelper.ACTIVITY_CONNECT_WIFI:
//                    String strIPAddress = "";
//                    String strPort = "";
//                    strIsConnected = data.getExtras().getString("is_connected");
//                    if (strIsConnected.equals("NO")) {
//                        txtTips.setText(thisCon.getString(R.string.activity_main_scan_error));
//                        return;
//                    } else {
//                        strIPAddress = data.getExtras().getString("IPAddress");
//                        strPort = data.getExtras().getString("Port");
//                        if (strIPAddress == null || !strIPAddress.contains("."))
//                            return;
//                        HPRTPrinter = new HPRTPrinterHelper(thisCon, spnPrinterList.getSelectedItem().toString().trim());
//                        if (HPRTPrinterHelper.PortOpen("WiFi," + strIPAddress + "," + strPort) != 0)
//                            txtTips.setText(thisCon.getString(R.string.activity_main_connecterr));
//                        else
//                            txtTips.setText(thisCon.getString(R.string.activity_main_connected));
//                        return;
//                    }
                case HPRTPrinterHelper.ACTIVITY_IMAGE_FILE:
//	  		    	PAct.LanguageEncode();
                    dialog = new ProgressDialog(Activity_Main.this);
                    dialog.setMessage("Printing.....");
                    dialog.setProgress(100);
                    dialog.show();
                    new Thread() {
                        public void run() {
                            try {
                                String strImageFile = data.getExtras().getString("FilePath");
                                Bitmap bmp = BitmapFactory.decodeFile(strImageFile);
                                int height = bmp.getHeight();
                                System.err.println("height:" + height);
                                HPRTPrinterHelper.printAreaSize("0", "200", "200", "" + height, "1");
                                int a = HPRTPrinterHelper.Expanded("0", "0", strImageFile);
                                if ("1".equals(Activity_Main.paper)) {
                                    HPRTPrinterHelper.Form();
                                }
                                HPRTPrinterHelper.Print();
                                if (a > 0) {
                                    handler.sendEmptyMessage(1);
                                } else {
                                    handler.sendEmptyMessage(0);
                                }
                            } catch (Exception e) {
                                handler.sendEmptyMessage(0);
                            }
                        }
                    }.start();
                    return;
                case HPRTPrinterHelper.ACTIVITY_PRNFILE:
                    String strPRNFile = data.getExtras().getString("FilePath");
                    HPRTPrinterHelper.PrintBinaryFile(strPRNFile);

	  				/*String strPRNFile=data.getExtras().getString("FilePath");
                      byte[] bR=new byte[1];
	  				byte[] bW=new byte[3];
	  				bW[0]=0x10;bW[1]=0x04;bW[2]=0x02;
	  				for(int i=0;i<Integer.parseInt(edtTimes.getText().toString());i++)
	  				{
	  					HPRTPrinterHelper.PrintBinaryFile(strPRNFile);
	  					HPRTPrinterHelper.DirectIO(bW, null, 0);
	  					HPRTPrinterHelper.DirectIO(null, bR, 1);
	  				}*/
                    return;
            }
        } catch (Exception e) {
            Log.e("HPRTSDKSample", (new StringBuilder("Activity_Main --> onActivityResult ")).append(e.getMessage()).toString());
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @SuppressLint("NewApi")
    public void onClickConnect(View view) {
        if (!checkClick.isClickEvent()) return;

        try {
            if (HPRTPrinter != null) {
                HPRTPrinterHelper.PortClose();
            }

            if (view.getId() == R.id.btnBT) {
                ConnectType = "Bluetooth";
                Intent serverIntent = new Intent(thisCon, Activity_DeviceList.class);
                startActivityForResult(serverIntent, HPRTPrinterHelper.ACTIVITY_CONNECT_BT);
                return;
            }
        } catch (Exception e) {
            Log.e("HPRTSDKSample", (new StringBuilder("Activity_Main --> onClickConnect " + ConnectType)).append(e.getMessage()).toString());
        }
    }

    private BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();
                if (ACTION_USB_PERMISSION.equals(action)) {
                }
                if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
                    device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (device != null) {
                        HPRTPrinterHelper.PortClose();
                    }
                }
            } catch (Exception e) {
                Log.e("HPRTSDKSample", (new StringBuilder("Activity_Main --> mUsbReceiver ")).append(e.getMessage()).toString());
            }
        }
    };
    private Button btnGetStatus;

    public void onClickClose(View view) {
        if (!checkClick.isClickEvent()) return;

        try {
            if (HPRTPrinter != null) {
                HPRTPrinterHelper.PortClose();
            }
            this.txtTips.setText(R.string.activity_main_tips);
            return;
        } catch (Exception e) {
            Log.e("HPRTSDKSample", (new StringBuilder("Activity_Main --> onClickClose ")).append(e.getMessage()).toString());
        }
    }

    public void onClickDo(View view) {
        if (!checkClick.isClickEvent()) return;

        if (!HPRTPrinterHelper.IsOpened()) {
            Toast.makeText(thisCon, thisCon.getText(R.string.activity_main_tips), Toast.LENGTH_SHORT).show();
            return;
        }
        String paper = PFun.ReadSharedPreferencesData("papertype");
        if (!"".equals(paper)) {
            Activity_Main.paper = paper;
        }
        if (view.getId() == R.id.btnQRCode) {
            //出库
            HPRTPrinterHelper.printAreaSize("0", "200", "200", "410", "1");
            if (OutStock != null && OutStock.equals("OutStock")) {

                PrintOutStock();

            } else {
                //装箱
                PrintSampleReceiptX();

                HPRTPrinterHelper.PrintQR(HPRTPrinterHelper.BARCODE, "385", "0", "2", "3", mFBillNo);

                // 打印文本
                PrintSampleReceipt();
                if (mFNumbers.length < 6) {
                } else {
                    PrintSampleReceipt1();
                }

                if ("1".equals(Activity_Main.paper)) {
                    HPRTPrinterHelper.Form();
                }
                HPRTPrinterHelper.Print();
                isSave = true;
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                        UIHelper.showSimpleBackTask(thisCon, SimpleBackPage.ZXST, null, "装箱");
                    }
                }, 1000);
            }
        }
    }

    /**
     * 装箱
     * 型号
     * 版本
     */
    private void PrintSampleReceiptX() {
        String[] Receipt = getResources().getStringArray(
                R.array.activity_main_sample_2inch_receipt);
        for (int i = 0; i < Receipt.length; i++) {
            HPRTPrinterHelper.PrintTextCPCL(HPRTPrinterHelper.TEXT, 24, "30", "" + (Integer.valueOf(2) + (i * 14) * 2), Receipt[i] + "" + mFXBWSX[i], 1, false, 100);
        }

    }

    /**
     * 出库单
     */
    private void PrintOutStock() {
        String[] Receipt = getResources().getStringArray(
                R.array.activity_main_sample);
        for (int i = 0; i < Receipt.length; i++) {
            HPRTPrinterHelper.PrintTextCPCL(HPRTPrinterHelper.TEXT, 24, "40", "" + (Integer.valueOf(2) + (i * 14) * 2), Receipt[i] + "" + mFOUT[i], 1, false, 100);
        }

        if ("1".equals(Activity_Main.paper)) {
            HPRTPrinterHelper.Form();
        }
        HPRTPrinterHelper.Print();

        isSave = true;
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                finish();
                UIHelper.showSimpleBackTask(thisCon, SimpleBackPage.OUTST, null, "出库");
            }
        }, 1000);
    }

    private void PrintSampleReceipt() {
        // HPRTPrinterHelper.printAreaSize("10", "300", "300", "310", "1");
        // HPRTPrinterHelper.AutLine("0", "0", 200, 8,ReceiptLines[i]);
        // HPRTPrinterHelper.AutCenter(HPRTPrinterHelper.TEXT, "0", "0", 100, 4,ReceiptLines[i]);
        // HPRTPrinterHelper.printAreaSize("0", "200", "200", "700", "1");
        //			HPRTPrinterHelper.PageWidth("1000");
        // HPRTPrinterHelper.LanguageEncode = "UTF-8";
//        HPRTPrinterHelper.Align(HPRTPrinterHelper.CENTER);
        HPRTPrinterHelper.SetSp("3");
        if (mFNumbers.length < 6) {
            for (int i = 0; i < mFNumbers.length; i++) {
                HPRTPrinterHelper.PrintTextCPCL(HPRTPrinterHelper.TEXT, 24, "100", "" + (Integer.valueOf(160) + (i * 16) * 2), mFNumbers[i], 1, false, 100);
            }
        } else {
            for (int i = 0; i < 6; i++) {
                HPRTPrinterHelper.PrintTextCPCL(HPRTPrinterHelper.TEXT, 24, "100", "" + (Integer.valueOf(160) + (i * 16) * 2), mFNumbers[i], 1, false, 100);
            }
        }
    }

    private void PrintSampleReceipt1() {
        String[] ReceiptLines = new String[(mFNumbers.length) - 6];
        System.arraycopy(mFNumbers, 6, ReceiptLines, 0, ReceiptLines.length);
        for (int i = 0; i < ReceiptLines.length; i++) {
            HPRTPrinterHelper.PrintTextCPCL(HPRTPrinterHelper.TEXT, 24, "280", "" + (Integer.valueOf(160) + (i * 16) * 2), mFNumbers[i], 1, false, 100);
        }
//        if ("1".equals(Activity_Main.paper)) {
//            HPRTPrinterHelper.Form();
//        }
//        HPRTPrinterHelper.Print();
//        finish();
    }

    private void CapturePrinterFunction() {
        try {
            int[] propType = new int[1];
            byte[] Value = new byte[500];
            int[] DataLen = new int[1];
            String strValue = "";
            boolean isCheck = false;
            if (PrinterName.equals("HM-T300") | PrinterName.equals("HM-A300") | PrinterName.equals("108B") | PrinterName.equals("R42") | PrinterName.equals("106B")) {
                btnCut.setVisibility(View.GONE);
                btnOpenCashDrawer.setVisibility(View.VISIBLE);
                btn1DBarcodes.setVisibility(View.VISIBLE);
                btnQRCode.setVisibility(View.VISIBLE);
                btnPageMode.setVisibility(View.GONE);
                btnPDF417.setVisibility(View.GONE);
                btnGetRemainingPower.setVisibility(View.GONE);
//				btnUSB.setVisibility(View.VISIBLE);
                btnBT.setVisibility(View.VISIBLE);
                btnSampleReceipt.setVisibility(View.VISIBLE);
                btnGetStatus.setVisibility(View.VISIBLE);
            }
        } catch (Exception e) {
            Log.e("HPRTSDKSample", (new StringBuilder("Activity_Main --> CapturePrinterFunction ")).append(e.getMessage()).toString());
        }
    }

}
